package com.example.yunxinagyue

import android.Manifest
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.media.MediaPlayer
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.MenuItem
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.io.*
import java.util.*
import kotlin.concurrent.thread

class MusicParam(var current:String, var process:Int):Serializable

var musicPathList= mutableListOf<String>()
var musicNameList= mutableListOf<String>()
var musicAlbumList= mutableListOf<String>()
var musicSingerList= mutableListOf<String>()
var musicParam=MusicParam("",0)
var current=3
class MusicPlaying : AppCompatActivity() {
    private val channelId = "weibo channel"
    private val notifyID = 1
    val mediaPlayer = MediaPlayer()
    private var isRunning=true
    private var count=0
    private var flag=true
    private var aiXinCount=0
    private var process=0
    @SuppressLint("UnspecifiedImmutableFlag")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_music_playing)
        val seekBar3 = findViewById<SeekBar>(R.id.seek_bar)
        val start = findViewById<Button>(R.id.start)
        val prev = findViewById<Button>(R.id.prev)
        val aiXin = findViewById<Button>(R.id.ai_xin)
        val next = findViewById<Button>(R.id.next)
        val backMusic = findViewById<Button>(R.id.back_music)
        loadData() ?. let {
            current=it.current.toInt()-1
            process=it.process
        } ?: let {
            current=3
            process=0
        }
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            getMusic()
        } else {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                1
            )
        }
        //        设置使用动画工具类创建动画，引入动画资源
        mediaPlayer.setOnPreparedListener {
            count = 0
            it.start()
            anim()
            seekBar3.max = mediaPlayer.duration
        }
        supportActionBar?.hide()
        start.setOnClickListener {
            if (count % 2 != 0) {
                mediaPlayer.start()
                flag=true
                start.setBackgroundResource(R.drawable.ic_play_music)
            } else {
                mediaPlayer.pause()
                flag=false
                start.setBackgroundResource(R.drawable.ic_bofang)
            }
            count++
            showImages()
            anim()
            notiy()
            Log.d("name", "---------------------$count-----------------------")
        }
        prev.setOnClickListener {
            current--
            flag=true
            aiXinCount=0
            aiXin.setBackgroundResource(R.drawable.ic_ai_xin)
            if (current <= 3) current = musicPathList.size
            play()
            start.setBackgroundResource(R.drawable.ic_play_music)
            anim()
            showImages()
            notiy()
        }
        next.setOnClickListener {
            current++
            flag=true
            aiXinCount=0
            aiXin.setBackgroundResource(R.drawable.ic_ai_xin)
            if (current == musicPathList.size) current = 3
            play()
            showImages()
            start.setBackgroundResource(R.drawable.ic_play_music)
            anim()
            notiy()
        }
        mediaPlayer.setOnCompletionListener {
            current++
            flag=true
            aiXinCount=0
            aiXin.setBackgroundResource(R.drawable.ic_ai_xin)
            if (current == musicPathList.size) current = 3
            play()
            start.setBackgroundResource(R.drawable.ic_play_music)
            showImages()
            anim()
            notiy()
        }
        seekBar3.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(p0: SeekBar?, process: Int, p2: Boolean) {
                if (p2) {
                    musicParam.process=process
                    mediaPlayer.seekTo(musicParam.process)
                }
            }

            override fun onStartTrackingTouch(p0: SeekBar?) {}
            override fun onStopTrackingTouch(p0: SeekBar?) {}
        })
        aiXin.setOnClickListener{
            if(aiXinCount%2==0){
                aiXin.setBackgroundResource(R.drawable.ic_aixin_1)
            }else{
                aiXin.setBackgroundResource(R.drawable.ic_ai_xin)
            }
            aiXinCount++
        }
        backMusic.setOnClickListener {
            val intent=Intent(this,FramlayoutActivity::class.java)
            startActivity(intent)
        }
        showImages()
        thread {
            while (isRunning) {
                val process = mediaPlayer.currentPosition
                seekBar3.progress = process
                Thread.sleep(600)
            }
        }
    }

    private fun anim(){
        val imageView = findViewById<ImageView>(R.id.music_cover)
        if(flag){
            val animation = AnimationUtils.loadAnimation(this, R.anim.rotate_img)
            val mode = LinearInterpolator()
            animation.interpolator = mode
            //动画旋转一圈所需时间
            animation.duration = 30000
//        设置重复模式为无限次
            animation.repeatMode = Animation.RESTART
//        设置动画无限次的重复次数
            animation.repeatCount = -1
//            animation.fillAfter=false
            imageView.startAnimation(animation)
        }else{
            imageView.clearAnimation()
        }
    }


    private fun notiy(){
//        设置通知步骤：
//        1：创建系统的通知管理器
//        2：指定通知的渠道
//        3：使用Notification.Builder创建通知
//        4：设置通知的属性和点击通知后进入的页面，使用意图
//        5：使用系统的通知管理器开启通知
        val notificationManager=getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val notificationChannel= NotificationChannel(channelId,"channel", NotificationManager.IMPORTANCE_HIGH)
        notificationManager.createNotificationChannel(notificationChannel)
        val builder= Notification.Builder(this,channelId)
        val intent= Intent(this,MusicPlaying::class.java)
        val pendingIntent= PendingIntent.getActivity(this,UUID.randomUUID().hashCode(),intent, PendingIntent.FLAG_IMMUTABLE)
        val no=builder.setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("云想乐")
            .setContentText("正在播放"+ musicNameList[current])
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .setWhen(System.currentTimeMillis())
            .build()
        notificationManager.notify(notifyID,no)
    }
    @SuppressLint("UseCompatLoadingForDrawables")
    fun showImages(){
        val images = findViewById<ImageView>(R.id.music_cover)
        if (current <= 3) {
            images.setImageDrawable(resources.getDrawable(R.drawable.five))
        } else if (current in 4..6) {
            images.setImageDrawable(resources.getDrawable(R.drawable.two))
        } else if (current in 7..9) {
            images.setImageDrawable(resources.getDrawable(R.drawable.five))
        } else if (current in 10..13) {
            images.setImageDrawable(resources.getDrawable(R.drawable.four))
        } else if (current in 14..16) {
            images.setImageDrawable(resources.getDrawable(R.drawable.one))
        } else if (current in 17..20) {
            images.setImageDrawable(resources.getDrawable(R.drawable.six))
        } else {
            images.setImageDrawable(resources.getDrawable(R.drawable.seven))
        }
    }

    @SuppressLint("SetTextI18n")
    fun play(){
        val musicName=findViewById<TextView>(R.id.musicName)
        val author=findViewById<TextView>(R.id.author)
        mediaPlayer.reset()
        mediaPlayer.setDataSource(musicPathList[current])
        mediaPlayer.prepareAsync()
        musicName.text= musicNameList[current]
        author.text= musicSingerList[current]
        count=0
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            androidx.appcompat.R.id.home -> finish()
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if(requestCode==1){
            if(grantResults.first()== PackageManager.PERMISSION_GRANTED){
                getMusic()
            }
        }
    }
    //进行外部存储
    private fun saveData(){
        //        使用外部存储将序列化后的对象存储在根目录下的user_info下
        val file = File(Environment.getExternalStorageDirectory().absolutePath)
        try {
            if(!file.exists()){
                file.mkdir()
                Log.d("n","----------------------------------------------------------------------")
                Log.d("xiaz","文件夹创建成功")
            }
            val newFile = File(Environment.getExternalStorageDirectory().absolutePath,"/music_info.txt")
            if(!newFile.exists()){
                newFile.createNewFile()
                Log.d("n","----------------------------------------------------------------------")
                Log.d("xiaz","文件创建成功")
            }
            val fos= ObjectOutputStream(FileOutputStream(newFile))
            fos.writeObject(musicParam)
            fos.flush()
            fos.close()
            Log.d("n","----------------------------------------------------------------------")
            Log.d("xiaz","已保存对象")
        }catch (e:Exception){
            e.printStackTrace()
        }

    }


    private fun loadData(): MusicParam? {
        return try {
            val file = File(Environment.getExternalStorageDirectory().absolutePath,"/music_info.txt")
            val fos= ObjectInputStream(FileInputStream(file))
            val obj=fos.readObject() as MusicParam
            fos.close()
            Log.d("n","----------------------------------------------------------------------")
            Log.d("xiazai","已下载对象")
            obj
        }catch (e:Exception){
            e.printStackTrace()
            null
        }
    }
    private fun getMusic() {
        val cursor=contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null,null,null,null)
        cursor?.apply {
            while(moveToNext()) {
                val musicPath=getString(getColumnIndexOrThrow(MediaStore.Audio.Media.DATA))
                val musicName=getString(getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE))
                val musicSinger=getString(getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST))
                val musicAlbum=getString(getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM))
                musicNameList.add(musicName)
                musicSingerList.add(musicSinger)
                musicAlbumList.add(musicAlbum)
                musicPathList.add(musicPath)
            }
            close()
        }
        Log.d("Main",musicNameList.toString())
        Log.d("Main",musicPathList.toString())
    }
    override fun onDestroy() {
        super.onDestroy()
        musicParam.current=current.toString()
        musicParam.process=process
        saveData()
        isRunning=false
        mediaPlayer.stop()
        mediaPlayer.release()
    }
}